/*
 * Copyright (c) 2013 TopCoder, Inc. All rights reserved.
 *
 */
/**
 * Show popup.
 *
 * @param {Object} selector the jQuery selector of the popup
 */
var showPopup = function(selector) {
    var body = $('body');
    $('.alpha').width(body.width()).height(body.height()).css('display', 'block');
    var popup = $(selector);
    popup.css('display', 'block').css('margin', -popup.height() / 2 + 'px 0 0 ' + (-popup.width() / 2) + 'px');
};
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var ajaxUpload = null;

/**
 * Show specified message with specified title.
 *
 * @param {String} title the title
 * @param {String} message the message
 */
function showMsg(title, message) {
    var parent = $('.popup__alert');
    parent.find('.popup__title-mid strong').html(title);
    parent.find('h4.popup__content-mid-tips').html(message);
    showPopup('.popup__alert');
}
$(function() {
    /**
     * Enable textbox with placeholder functionality.
     *
     * @param {String} selector the jQuery selector of the textbox
     * @param {String} text the placeholder text
     */
    var initPlaceHolder = function(selector, text) {
        $(selector).live('focus', function() {
            $(this).live('blur', function() {
                $(this).unbind('blur', arguments.callee);
                if ($(this).val() == '') {
                    $(this).val(text);
                }
            });
            if ($(this).val() == text) {
                $(this).val('');
            }
        });
    };
    initPlaceHolder('.search-friend input', 'Search');
    initPlaceHolder('.search-box input', 'Search Members');
    initPlaceHolder('.js-post-comment', 'post comment here');
    initPlaceHolder('.login input[type="text"]', 'Username here');
    initPlaceHolder('.friend-user__search-input', 'Search');
    initPlaceHolder('.reply-area', 'Write a reply...');
    initPlaceHolder('.recovery #username', 'Username here');
    initPlaceHolder('.recovery #email', 'email');
    initPlaceHolder('.recovery #email2', 'email');
    initPlaceHolder('.recovery #handle', 'Username here');
    initPlaceHolder('.profile-message__breadcrumb .text', 'Search another..');

    var mockInputText = ['Angel', 'Anggie', 'Angle', 'Angora', 'Angella', 'Uncle'];
    $('.search-box').delegate('.auto-complete li', 'click', function() {
        if ($(this).hasClass('last-li')) {
            return;
        }
        var text = $(this).text();
        $('.search-box input').val(text);
    });
    /**
     * Event handler of input change event.
     *
     * @param {Object} input the input field
     */
    function onInputChange(input) {
        var value = input.val();
        var parent = input.parent();
        if (!value || value.length < 3) {
            // Remove the auto complete.
            $('.auto-complete', parent).hide();
        } else {
            $.ajax({
                url : '/membersearch?ajax=true&member=' + value,
                type : 'GET',
                dataType : 'json',
                success : function(res) {
                    var list = $('.auto-complete', parent);
                    if (list.length > 0) {
                        list.remove();
                    }
                    list = $('<ul class="auto-complete"></ul>');
                    parent.append(list);
                    list.empty();
                    $.each(res.users, function(idx, user) {
                        var reg = new RegExp(value, 'ig');
                        var result = reg.exec(user.username);
                        if (result) {
                            var found = result[0];
                            var index = result['index'];
                            var source = result['input'];

                            var len1 = found.length;
                            source = '<li><img src="/i/user-photo-small.png" alt="" /><a href="#" class="link-user">' + user.username.substring(0, index - 1) + '<strong>' + found + '</strong>' + source.substring(index + len1) + '</a></li>';
                            list.append(source);
                        }
                    });

                    if (list.find('li').length > 0) {
                        list.append('<li class="last-li"><a href="javascript:searchMember();" class="go-searchs">See more results for <strong>' + value + '</strong></a></li>');
                        list.show();
                    } else {
                        list.hide();
                    }
                },
                error : function() {
                    showMsg('ALERT', 'Can not get user suggestions!!!');
                }
            });
        }
    }

    $('.search-box input').keyup(function(e) {
        onInputChange($(this));
    }).mouseup(function(e) {
        onInputChange($(this));
    }).blur(function(e) {
        var that = $(this);
        window.setTimeout(function() {
            that.parent().find('.auto-complete').hide();
        }, 200);
    });
    var lastText = '';

    /**
     * Event handler of filter change event.
     *
     * @param {Object} input the input field
     */
    function onFilterChange(input) {
        var parent = input.parent().parent();
        parent.find('.is-lazy-load').remove();
        var friendItem = parent.find('.js-friend-list-item');
        parent.find('.friend-user__list').scrollTop(0);
        var text = input.val();
        text = text.toLowerCase();
        friendItem.each(function() {
            var value = $(this).find('.friend-user__list-item__user').text();
            value = value.toLowerCase();
            if (value.indexOf(text) >= 0) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
        if (parent.find('.js-friend-list-item:visible').length < 12) {
            parent.find('.js-msg-load-more').attr('disabled', 'disabled').hide();
        } else {
            parent.find('.js-msg-load-more').removeAttr('disabled').show();
        }
        var activeRow = parent.find('.is-selected:visible');
        if (activeRow.length > 0) {
        } else {
            parent.find('.is-selected').removeClass('is-selected');
            $('.message__list').addClass('is-hidden');
            $('.message__reply-msg-bar').addClass('is-hidden');
        }
        handleScrollLoading(parent);
    }

    $('.friend-user__search-input').focus(function() {
        var $input = $(this);
        window.filterTicks = window.setInterval(function() {
            var text = $input.val();
            if (lastText != text) {
                lastText = text;
                onFilterChange($input);
            }
        }, 100);
    }).blur(function() {
        if (window.filterTicks) {
            window.clearInterval(window.filterTicks);
        }
    });

    $('.js-msg-load-more').each(function() {
        var parent = $(this).parent();
        handleScrollLoading(parent);
    });

    var testMac = /Mac OS X/;
    var userAgent = navigator.userAgent;
    var isIE = $.browser.msie;
    var IEVersion = $.browser.version;
    if (testMac.test(userAgent) || (isIE && IEVersion == '9.0')) {
        $('.box__title ul li a').addClass('mac-fix');
    }
    /**
     * Get text from a value.
     * @param {Mixed} val the value
     * @return {String} the value as string
     */
    function getTxt(val) {
        return val ? val : '';
    }
    // use jqtransform to style all form elements
    if ($('.js-jqtransform').length > 0) {
        $('.js-jqtransform').jqTransform();
    }
    $(document).delegate('.js-send-user-msg', 'click', function() {
        var parent = $('.popup--send-message');
        var username = $(this).data('username');
        var userId = $(this).data('userid');
        parent.find('#to').val(username);
        parent.find('#toUserId').val(userId);
        parent.find('.photos').empty();
        parent.find('#message').val('');
        ajaxUpload._settings.action = '/social/attachments/' + username;
        showPopup('.popup--send-message');
    });

    $('.js-chk').click(function() {
        $(this).toggleClass('is-checked');
        if ($(this).hasClass('js-chk-all')) {
            var id = $(this).attr('id').replace('-alt', '');
            if ($(this).hasClass('is-checked')) {
                $('.' + id + ':visible').addClass('is-checked');
            } else {
                $('.' + id + ':visible').removeClass('is-checked');
            }
        } else {
            if($('#notificationDataTable').length) {
                if($(this).parents('tbody').find('tr a.js-chk.is-checked').length ==
                    $(this).parents('tbody').find('tr a.js-chk').length) {
                    $(this).parents('table').find('thead .js-chk-all').addClass('is-checked');
                } else {
                    $(this).parents('table').find('thead .js-chk-all').removeClass('is-checked');
                }
            }
            if($('#sharingOptionsDataTable').length) {
                var idx = $(this).parents('tr').find('a.js-chk').index($(this));
                var allChecked = true;
                $(this).parents('tbody').find('tr').each(function(i, row) {
                    if(!$(row).find('a:eq(' + idx + ')').hasClass('is-checked')) {
                        allChecked = false;
                        return false;
                    }
                });
                if(allChecked) {
                    $(this).parents('table').find('thead a:eq(' + idx + ').js-chk-all').addClass('is-checked');
                } else {
                    $(this).parents('table').find('thead a:eq(' + idx + ').js-chk-all').removeClass('is-checked');
                }
            }
        }
    });
    $('.js-radio').click(function() {
        if ($(this).hasClass('is-checked')) {
            return;
        }
        $(this).parent().find('.is-checked').removeClass('is-checked');
        $(this).addClass('is-checked');
    });
    /**
     * Append shadow.
     *
     * @param {Object} inst the instance
     */
    function appendShadow(inst) {
        var dpDiv = inst.dpDiv;
        if (dpDiv.length > 0) {
            // Check if it is hacked.
            var shadow = dpDiv.find('.shadow');
            if (shadow.length <= 0) {
                var shadowStr =     '<div class="dp-shadow">'
                                +        '<div class="shadow-top-left"></div>'
                                +        '<div class="shadow-top-right"></div>'
                                +        '<div class="shadow-top"></div>'
                                +        '<div class="shadow-left"></div>'
                                +        '<div class="shadow-right"></div>'
                                +        '<div class="shadow-bottom-left"></div>'
                                +        '<div class="shadow-bottom"></div>'
                                +        '<div class="shadow-bottom-right"></div>'
                                +    '</div>';
                shadow = $(shadowStr);
                dpDiv.find('.ui-datepicker-header').append('<div class="datepicker-triangle"></div>');
                dpDiv.append(shadow);
                if ($.browser.msie) {
                    dpDiv.css('height', 'auto');
                    dpDiv.height(dpDiv.height());
                }
            }
        }
    }
    $('.js-calendar').each(function() {
        $(this).datepicker({
            showOn: 'both',
            buttonImage: '/i/calendar.png',
            buttonImageOnly: true,
            onShow: appendShadow,
            positionAdjust: true,
            dateFormat: 'mm/dd/y',
            defaultDate: '02/21/88'
        });
    });

    if ($.browser.mozilla) {
        $('.item-birth img').addClass('fix-ff');
        $('.user-profile-description').css('padding-bottom', '19px');
    }

    // own profile navigation
    $('.js-navi-wall').bind('click', function() {
        $('.box__title-navi .is-active').removeClass('is-active');
        $(this).addClass('is-active');
        $('.js-profile-friends').addClass('is-hidden');
        $('.js-profile-wall').removeClass('is-hidden');
    });
    $('.js-navi-friends').bind('click', function() {
        $('.box__title-navi .is-active').removeClass('is-active');
        $(this).addClass('is-active');
        $('.js-profile-wall').addClass('is-hidden');
        $('.js-profile-friends').removeClass('is-hidden');
    });
    $('.js-navi-messages').click(function() {
        $('.box__title-navi .is-active').removeClass('is-active');
        $(this).addClass('is-active');
        $('.js-profile-subpanel').addClass('is-hidden');
        $('.js-profile-messages').removeClass('is-hidden');
    });
    $('.js-tab').click(function() {
        var p = $(this).parent().parent().find('.is-active');
        p.removeClass('is-active');
        $(this).addClass('is-active');
        var text = $(this).text();
        var subpane = null;
        switch (text) {
            case 'PERSONAL WALL':
                subpane = $('.js-wall');
                break;
            case 'USER PROFILE':
                subpane = $('.js-user-profile');
                break;
        }
        if (subpane) {
            subpane.siblings('.js-subpane').addClass('is-hidden');
            subpane.removeClass('is-hidden');
        }
    });
    $('.js-navi').click(function() {
        if($(this).parents('.privte-profile').length) {
            return;
        }
        var active = $(this).parent().parent().find('.is-active');
        var activeId = active.attr('id');
        var tid = $(this).attr('id');
        if (activeId == tid) {
            return;
        }
        active.removeClass('is-active');
        $(this).addClass('is-active');
        var pid = tid.replace('js-navi-', '');
        $('.private-profile-subpanel').addClass('is-hidden');
        $('.private-profile-subpanel.js-private-profile-' + pid).removeClass('is-hidden');

    });
    $('.js-share-filter').click(function() {
        $(this).parent().find('.is-active').removeClass('is-active');
        $(this).addClass('is-active');
        var text = $(this).text().replace('Share User ', '').replace('Share ', '');
        var parent = $(this).parents('.js-private-profile-sharing').eq(0);
        var title = parent.find('th.table-col-first div');
        title.text(text + ' Name');

        if (text == 'Profile') {
            $('.js-filter-profile').show();
            $('.js-filter-profile td').show();
            $('.js-filter-activity').hide();
            $('.js-filter-activity td').hide();
            $('.profile-tr').show();
            $('.act-tr').hide();
        } else {
            $('.js-filter-profile').hide();
            $('.js-filter-profile td').hide();
            $('.js-filter-activity').show();
            $('.js-filter-activity td').show();
            $('.profile-tr').hide();
            $('.act-tr').show();
        }
    });

    $('.js-btn-unregister').click(function() {
        showPopup('.popup__unregister-profile');
    });

    $('.js-new-message').click(function() {
        showPopup('.popup--send-message');
    });

    $(document).delegate('.js-friend-list-item', 'click', function() {
        if ($(this).hasClass('is-selected')) {
            return;
        }
        $(this).addClass('is-selected');
        $(this).siblings('.is-selected').removeClass('is-selected');
        $('.message__list').removeClass('is-hidden');
        $('.message__list').find('.js-mock-new').remove();
        $('.message__reply-msg-bar').removeClass('is-hidden');
        $('.message__reply-msg-bar .reply-area').val('Write a reply...');
        $('.message__list .is-lazy-load').remove();
        handleScrollLoading($('.message__list'));
    });
    $('.js-friend-list-item').hover(
        function() {
            $(this).addClass('is-hover');
        },
        function() {
            $(this).removeClass('is-hover');
        }
    );
    $('.link-private-profile__title').click(function() {

        var parent = $(this).parent().parent();
        parent.addClass('is-edit-mode');
        parent.find('.is-symbol-checked').each(function() {
            if ($(this).hasClass('is-symbol-unchecked')) {
                $(this).next().removeClass('is-checked');
            } else {
                $(this).next().addClass('is-checked');
            }
        });
        parent.find('.email-format').each(function() {
            var text = $(this).text();
            $(this).next().find('a').each(function() {
                if ($(this).text() == text) {
                    $(this).addClass('is-checked');
                } else {
                    $(this).removeClass('is-checked');
                }
            });
        });

        var target = parent.find('.private-profile__content-edit');
        parent.find('.private-profile__content dd').each(function() {
            var p = $(this);
            var labels = p.attr('class')
            if (!labels) {
                return;
            }
            labels = labels.split(' ');
            var key = '';
            for (var i = 0; i < labels.length; i++) {
                var label = labels[i];
                if (label.indexOf('js-item-') >= 0) {
                    key = label;
                    break;
                }
            }
            if (key.length > 0) {
                var targetwrapper = target.find('.' + key);
                var control = targetwrapper.find('textarea, input');

                if (control.hasClass('js-calendar')) {
                    var value = $(this).text();
                    var date = $.datepicker.parseDate('MM dd, yy', value);
                    control.datepicker('setDate', date);
                } else {
                    if (control.hasClass('textarea-bio')) {
                        var text = $.trim($(this).html());
                        text = text.replace(/[<]br[/][>]/gi, '\n');
                        text = text.replace(/\<br\>/gi, '\n');
                        control.val(text);
                    } else {
                        control.val($(this).text());
                    }
                }
            }
        });
    });

    $('.js-reply-message').click(function() {
        var content = $(this).siblings('textarea').val();
        if (content == '' || content == 'Write a reply...') {
            return;
        }

        var list = $(this).parent().siblings('.message__list');
        var items = $('<div class="message__list__item-sent js-mock-new js-cache-load"><img src="/i/user-photo-small.png" alt="Photo"><div class="message__list__item-area"><a href="UserProfile-user\'sownprofilepage.html" class="link-user">MyName</a><p>' + content + '</p><div class="message__list__item-timestamp">12/12/12 03:23 AM</div></div></div>');
        list.prepend(items);
    });
    /**
    $('.private-profile__content-edit__button-bar a.js-button-save').click(function() {

        var parent = $(this).parent().parent().parent();
        parent.find('.is-symbol-checked').each(function() {
            var next = $(this).next();
            if (next.hasClass('is-checked')) {
                $(this).removeClass('is-symbol-unchecked');
            } else {
                $(this).addClass('is-symbol-unchecked');
            }
        });
        parent.find('.email-format').each(function() {
            $(this).text($(this).next().find('a.is-checked').text());
        });

        var target = parent.find('.private-profile__content');

        parent.find('input, textarea').each(function() {
            var p = $(this).parent();
            var labels = p.attr('class')
            if (!labels) {
                return;
            }
            labels = labels.split(' ');
            var key = '';
            for (var i = 0; i < labels.length; i++) {
                var label = labels[i];
                if (label.indexOf('js-item-') >= 0) {
                    key = label;
                    break;
                }
            }
            if (key.length > 0) {
                var itemwrapper = target.find('.' + key);
                var a = itemwrapper.find('a');
                if (a.length > 0) {
                    a.attr('href', 'mailto:' + $(this).val());
                    a.text($(this).val());
                } else {
                    if ($(this).hasClass('js-calendar')) {
                        var date = $(this).datepicker('getDate');
                        var str = $.datepicker.formatDate('MM dd, yy', date);
                        itemwrapper.text(str);
                    } else {
                        if ($(this).hasClass('textarea-bio')) {
                            var str = $(this).val().replace(/\n/g, '<br>');
                            itemwrapper.html(str);
                        } else {
                            itemwrapper.text($(this).val());
                        }
                    }
                }
            }
        });
        parent.removeClass('is-edit-mode');
    });
    */
    $('.private-profile__content-edit__button-bar a.js-button-cancel').click(function() {
        var parent = $(this).parent().parent().parent();
        parent.removeClass('is-edit-mode');
    });

    // hide header popup by clicking outside of it
    var hideHeaderPopup = function(e) {
        if ($('.header-popup:visible').length > 0 && !$(e.target).hasClass('header-popup') && $(e.target).parents('.header-popup').length < 1) {
            $(window).unbind('click', hideHeaderPopup);
            $('.header-popup').css('display', 'none');
        }
    };
    // header popup
    $('.l-header .logged-in .icon').bind('click', function(e) {
        e.stopImmediatePropagation();
        var popup = $(this).siblings('.header-popup');
        $(window).unbind('click', hideHeaderPopup);
        $(this).parent().siblings().children('.header-popup').css('display', 'none');
        if (popup.css('display') == 'none') {
            popup.css('display', 'block');
            $(window).bind('click', hideHeaderPopup);
        } else {
            popup.css('display', 'none');
            $(window).unbind('click', hideHeaderPopup);
        }
    });

    // popup
    $('.popup .close-btn, .popup--add-friend .cancel-btn, .popup--send-message .cancel-btn, .js-no, .popup__remove-friend .js-yes, .popup__confirm-friend .js-yes, .popup__block-friend .js-yes, .popup__unblock-friend .js-yes, .popup__alert .js-ok').bind('click', function() {
        $('.alpha').css('display', 'none');
        $(this).parents('.popup').css('display', 'none');
    });
    $(document).delegate('.js-remove-friend', 'click', function() {
        var parent = $('.popup__remove-friend');
        parent.find('.confirmRemoveFriend').attr('name', $(this).attr('name'));
        parent.find('.confirmRemoveFriend').data('friend', $(this).data('friend'));
        if($(this).hasClass('ignore-friend')) {
            parent.find('.popup__title-mid strong').html('IGNORE FRIEND');
            parent.find('h4.popup__content-mid-tips').html('Are you sure to ignore this friend?');
        } else {
            parent.find('.popup__title-mid strong').html('REMOVE FRIEND');
            parent.find('h4.popup__content-mid-tips').html('Are you sure to remove this friend?');
        }
        showPopup('.popup__remove-friend');
    });
    $(document).delegate('.js-confirm-friend', 'click', function() {
        var parent = $('.popup__confirm-friend');
        parent.find('.confirmConfirmFriend').attr('name', $(this).attr('name'));
        parent.find('.confirmConfirmFriend').data('friend', $(this).data('friend'));
        showPopup('.popup__confirm-friend');
    });
    $(document).delegate('.js-block-friend', 'click', function() {
        var parent = $('.popup__block-friend');
        parent.find('.confirmBlockFriend').attr('name', $(this).attr('name'));
        parent.find('.confirmBlockFriend').data('friend', $(this).data('friend'));
        showPopup('.popup__block-friend');
    });
    $(document).delegate('.js-unblock-friend', 'click', function() {
        var parent = $('.popup__unblock-friend');
        parent.find('.confirmUnblockFriend').attr('name', $(this).attr('name'));
        parent.find('.confirmUnblockFriend').data('friend', $(this).data('friend'));
        showPopup('.popup__unblock-friend');
    });
    $('.js-sign-in').bind('click', function(){
        showPopup('.popup--login');
    });
    $('.js-send-message').bind('click', function() {
        showPopup('.popup--send-message');
    });

    $(document).delegate('.js-add-friend', 'click', function() {
        if($(this).hasClass('addFriendFromSearch')) {
            var parent = $(this).parents('.js-friend-request').eq(0);
            var username = parent.find('.username').html();
            var userId = parent.find('.userId').val();
            $('.popup--add-friend').find('.messageTitle').html(username + ' will have to confirm that you are friends.');
            $('#addFriendId').val(userId);
            $('#addFriendUsername').val(username);
        }
        showPopup('.popup--add-friend');
    });
    $('.popup__unregister-profile .js-yes').bind('click', function() {
        $('.alpha').css('display', 'none');
        $('.popup__unregister-profile').css('display', 'none');
        unregisterUser();
    });
    /**
     * Change content of home carousel.
     * @param {Number} index the index of the current content
     */
    var changeContent = function (index) {
        var index = $.jcarousel.intval($('.carousel .is-current').attr('jcarouselindex'));
        index = (index - 1) % 5;
        index = index < 0 ? 5 + index : index;
        $('.home-carousel .content:visible').fadeOut('fast', function() {
            $('.home-carousel .content:eq(' + index + ')').fadeIn('fast');
        });
    };
    if ($('.carousel').length > 0) {
        var isFinished = true; // is used to ensure the animation has finished before doing anything else
        $('.carousel ul').jcarousel({
            vertical: true,
            scroll: 1,
            wrap: 'circular',
            setupCallback: function() {
                // add current style
                $('.carousel ul li:eq(2)').addClass('is-current');
                $('.jcarousel-list-vertical').css('overflow','auto');
                $('.jcarousel-list-vertical').css('overflow-y','hidden');
                $('.jcarousel-list-vertical').css('padding','0 18px 0 35px');
                // ride the carousel
                $('.jcarousel-prev-vertical').live('click', function() {
                    if (isFinished) {
                        isFinished = false;
                        $('.carousel ul li.is-current').prev().addClass('is-current');
                        $('.carousel ul li.is-current:eq(1)').removeClass('is-current');
                        changeContent();
                    }
                });
                $('.jcarousel-next-vertical').live('click', function() {
                    if (isFinished) {
                        isFinished = false;
                        $('.carousel ul li.is-current').next().addClass('is-current');
                        $('.carousel ul li.is-current:eq(0)').removeClass('is-current');
                        changeContent();
                    }
                });
            },
            itemFirstInCallback: function() {
                isFinished = true;
            },
            initCallback: function(carousel){
                // click on the item
                $('.carousel ul li').bind('click', function() {
                    var index = $.jcarousel.intval($(this).attr('jcarouselindex'));
                    $(this).addClass('is-current');
                    $(this).siblings().removeClass('is-current');
                    carousel.scroll($.jcarousel.intval($(this).attr('jcarouselindex') - 2));
                    changeContent();
                });
            }
        });
    }

    // show/hide comment
    $('.buttons .js-show-comment').live('click', function() {
        var self = $(this);
        if (!self.hasClass('active')) {
            self.addClass('active');
            self.parents().next('.feed-comment').removeClass('is-hidden');
        } else {
            self.removeClass('active');
            self.parents().next('.feed-comment').addClass('is-hidden');
        }
    });

    // load more
    if ($('.load-more:visible').length > 0) {
        var isLoading = false;
        var isNoMore = false;    // for demonstrate no more items to load only
        $(window).bind('scroll', function () {
            var callee = arguments.callee;
            if ($(window).scrollTop() + $(window).height() >= $('.load-more:visible').offset().top && !isLoading) {
                isLoading = true;
                // replace your code here and remember to set 'isLoading' to false when content has been loaded and no more items to load
                var i = 0;
                var int = setInterval(function () {
                    if (i > 2) {
                        clearInterval(int);
                        if (isNoMore) {    // no more items
                            var prev = $('.load-more:visible').prev();
                            while (prev.css('display') == 'none' || prev.hasClass('feed-comment')) {
                                prev = prev.prev();
                            }
                            prev.addClass('last-item');
                            $('.load-more:visible').remove();
                            $(window).unbind('scroll', callee);
                        } else {
                            if($('.load-more').hasClass('more-searched-users')) {
                                var pageNumber = parseInt($('#pageNumber').val(), 10) + 1;
                                var member = $('#searchMemberKeyword').val();
                                $.ajax({
                                    url : '/moremembers?member=' + member + '&pageNumber=' + pageNumber,
                                    type : 'GET',
                                    dataType : 'json',
                                    success : function(res) {
                                        if(res.users.length == 0) {
                                            isNoMore = true;
                                            return;
                                        }
                                        $('#pageNumber').val(pageNumber);
                                        $.each(res.users, function(idx, user) {
                                            var roles = [];
                                            for(var i = 0; i < user.roles.length; i++) {
                                                var role = user.roles[i];
                                                roles.push(role.name);
                                            }
                                            var addFriendBlock = '';
                                            if(res.loggedIn && !user.isOwner && !user.isFriend) {
                                                addFriendBlock = '<a class="button float-right js-add-friend addFriendFromSearch" href="javascript:;">ADD AS FRIEND</a>';
                                            }
                                            var content =
                                                '<div class="friend-request js-friend-request clearfix friend-request--profile">' +
                                                    '<a class="friend-request__photo float-left" href="/userPublicProfile/' + user.username + '">' +
                                                    '<img style="width: 80px; height: 74px;" alt="Username" src="' + (user.photo ? user.photo : "/i/popup-photo.png") + '" />' +
                                                    '</a>' +
                                                    '<div class="friend-request__content">' + addFriendBlock +
                                                    '<a class="username" href="/userPublicProfile/' + user.username + '">' + user.username + '</a>' +
                                                    '<input type="hidden" class="createdDate" value="' + user.createdDate + '">' +
                                                    '<input type="hidden" class="userId" value="' + user.id + '">' +
                                                    '<span class="user-type">' + roles.join(', ') + '</span>' +
                                                    '</div>' +
                                                    '</div>';
                                            $('.load-more:visible').before(content);
                                        });
                                    },
                                    error : function() {
                                        showMsg('ALERT', 'Can not get user suggestions!!!');
                                    }
                                });
                            } else if($('.load-more').parents('.js-profile-friends').length) {
                                var pageNumber = parseInt($('.friendsPageNumber').val(), 10) + 1;
                                var block = $('.friends-type-filter .blockedFriends').hasClass('is-tab-selected');
                                $.ajax({
                                    url : '/social/moreFriends',
                                    type : 'POST',
                                    dataType : 'json',
                                    contentType : "application/json; charset=utf-8",
                                    data : JSON.stringify({
                                        username : $('#username').val(),
                                        pageNumber : pageNumber,
                                        block : block
                                    }),
                                    success : function(res) {
                                        var friends = res.friends;
                                        $('.friendsPageNumber').val(pageNumber);
                                        var count = parseInt($('.friendsCount').val(), 10);
                                        $('.friendsCount').val(count + friends.length);
                                        if(friends.length == 0) {
                                            isNoMore = true;
                                            return;
                                        }
                                        for(var i = 0, l = friends.length; i < l; i++) {
                                            var friend = friends[i];
                                            var content = '';
                                            if(block) {
                                                content =
                                                '<div class="friend-request js-friend-request clearfix friend-request--profile">' +
                                                    '<input type="hidden" class="createdDate" value="' + friend.createdDate + '">' +
                                                    '<a class="friend-request__photo float-left" href="/userPublicProfile/' + friend.username + '">' +
                                                        '<img alt="' + friend.username + '" src="' +
                                                        ((!friend.photo) ?
                                                            '/i/popup-photo.png' : friend.photo) + '" style="width: 80px; height: 74px;" />' +
                                                        '</a>' +
                                                    '<div class="friend-request__content">' +
                                                        '<a class="button float-right js-unblock-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '">UNBLOCK</a>' +
                                                        '<a class="button float-right js-remove-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '">REMOVE FRIEND</a>' +
                                                        '<a class="username" href="/userPublicProfile/' + friend.username + '">' + friend.username + '</a>' +
                                                        '<span class="user-type">' + friend.roles + '</span>' +
                                                    '</div>' +
                                                '</div>';
                                            } else {
                                                content =
                                                '<div class="friend-request js-friend-request clearfix friend-request--profile">' +
                                                    '<input type="hidden" class="createdDate" value="' + friend.createdDate + '">' +
                                                    '<a class="friend-request__photo float-left" href="/userPublicProfile/' + friend.username + '">' +
                                                        '<img alt="' + friend.username + '" src="' +
                                                            ((!friend.photo) ?
                                                                '/i/popup-photo.png' : friend.photo) + '" style="width: 80px; height: 74px;" />' +
                                                    '</a>';
                                                    if(friend.active) {
                                                        content +=
                                                        '<div class="friend-request__content">' +
                                                            '<a class="button float-right js-block-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '">BLOCK</a>' +
                                                            '<a class="button float-right js-remove-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '">REMOVE FRIEND</a>' +
                                                            '<a href="javascript:;" class="button float-right js-send-user-msg" data-userId="' + friend.userId + '" data-username="' + friend.username + '">MESSAGE</a>' +
                                                            '<a class="username" href="/userPublicProfile/' + friend.username + '">' + friend.username + '</a>' +
                                                            '<span class="user-type">' + friend.roles + '</span>' +
                                                        '</div>';
                                                    } else {
                                                        content +=
                                                            '<div class="friend-request__content">' +
                                                                '<a class="button float-right js-confirm-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '" data-userId="' + friend.userId + '">CONFIRM FRIEND</a>' +
                                                                '<a class="button float-right js-remove-friend ignore-friend" href="javascript:;" name="' + friend.friendId + '" data-friend="' + friend.username + '">IGNORE FRIEND</a>' +
                                                                '<a href="javascript:;" class="button float-right js-send-user-msg" data-userId="' + friend.userId + '" data-username="' + friend.username + '">MESSAGE</a>' +
                                                                '<a class="username" href="/userPublicProfile/' + friend.username + '">' + friend.username + '</a>' +
                                                                '<span class="user-type">' + friend.roles + '</span>' +
                                                            '</div>';
                                                    }
                                                    content += '</div>';
                                            }
                                            $('.load-more:visible').before(content);
                                        }
                                    }
                                });
                            } else if($('.load-more').parents('.js-profile-wall').length) {
                                var pageNumber = parseInt($('.wallPostsPageNumber').val(), 10);
                                $('.wallPostsPageNumber').val(pageNumber + 1);
                                $.post('/personalWall/moreWallPosts', {
                                    username : $('#username').val(),
                                    pageNumber : pageNumber + 1
                                }).success(function(res) {
                                        res = JSON.parse(res);
                                        var userActivities = res.userActivities;
                                        var count = parseInt($('.wallPostsCount').val(), 10);
                                        $('.wallPostsCount').val(count + userActivities.length);
                                        if($('.wallPostsTotal').val() <= $('.wallPostsCount').val()) {
                                            isNoMore = true;
                                        }
                                        for(var i = 0, l = userActivities.length; i < l; i++) {
                                            var activity = userActivities[i];
                                            var content = '';
                                            if(activity.userWallPost) {
                                                var post = activity.userWallPost;
                                                content =
                                                    '<div class="feeds"><img class="feeds__photo float-left" alt="tcUser" src="' + (post.icon ? post.icon : '/i/feed-photo.png') + '">' +
                                                        '<div class="feeds__content clearfix">' +
                                                            '<p class="action">' +
                                                                '<span class="time float-right">' + getTxt(post.modifiedDate) + '</span>' +
                                                                '<a class="link" href="">' + post.username + '</a>&nbsp;' + post.summary +
                                                            '</p>' +
                                                            '<p><textarea class="textarea self-comment" disabled="disabled" rows="" cols="" style="resize: none;">' + getTxt(post.detail) + '</textarea></p>';
                                                if(post.username === res.username) {
                                                    content +=
                                                        '<div class="edit">' +
                                                            '<input type="hidden" class="wallPostId" value="' + post._id + '" />' +
                                                            '<a class="js-edit-comment" href="javascript:;">Edit</a>&nbsp;|&nbsp;' +
                                                            '<a class="js-remove-comment" href="javascript:;">Remove</a>' +
                                                        '</div>';
                                                } else {
                                                    content += '<input type="hidden" class="wallPostId" value="' + post._id + '" />';
                                                }
                                                content +=
                                                    '<div class="buttons buttons--self-comment">';
                                                if('true' === $('#canViewComments').val()) {
                                                    content += '<a class="comment js-show-comment comment-count" href="javascript:;">' + post.comments.length + '</a>';
                                                }
                                                content +=
                                                    '<a class="like" href="javascript:;">0</a>' +
                                                        '<a class="tweet" href="javascript:;">0</a>' +
                                                    '</div></div></div>';
                                                if('true' === $('#canViewComments').val()) {
                                                    content +=
                                                        '<ul class="feed-comment is-hidden">';
                                                    for(var j = 0; j < post.comments.length; j++) {
                                                        var comment = post.comments[j];
                                                        content +=
                                                            '<li class="clearfix">' +
                                                                '<img alt="" src="/i/comment-photo.png" />' +
                                                                '<a class="link" href="/userPublicProfile/' + comment.user + '">' + comment.user + '</a>';
                                                        if(comment.user === res.username) {
                                                            content +=
                                                                '<p><textarea class="textarea self-comment" disabled="disabled" rows="" cols="" style="resize: none;">' + comment.text + '</textarea>' +
                                                                '</p>' +
                                                                '<div class="editComment">' +
                                                                    '<input type="hidden" class="wallPostCommentId" value="' + comment._id + '" />' +
                                                                    '<a class="js-edit-post-comment" href="javascript:;">Edit</a>&nbsp;|&nbsp;' +
                                                                    '<a class="js-remove-post-comment" href="javascript:;">Remove</a>' +
                                                                '</div>';
                                                        } else {
                                                            content += '<p>' + comment.text + '</p>';
                                                        }
                                                        content +='</li>';
                                                    }
                                                    content +=
                                                            '<li class="clearfix">' +
                                                                '<img alt="" src="/i/comment-photo.png" />' +
                                                                '<textarea class="textarea js-post-comment" style="resize: none;" rows="" cols="">post comment here</textarea>' +
                                                            '</li>' +
                                                        '</ul>';
                                                }
                                            } else {
                                                content =
                                                    '<div class="feeds">' +
                                                        '<img class="feeds__photo float-left" src="/i/feed-photo.png" alt="tcUser">' +
                                                        '<div class="feeds__content clearfix">' +
                                                            '<p class="action">' +
                                                                '<span class="time float-right">&nbsp;</span>' +
                                                                '<a class="link" href="/userProfile/' + activity.user + '">' + activity.user + '</a>' +
                                                                    '&nbsp;' + activity.text +
                                                            '</p>' +
                                                        '</div>' +
                                                    '</div>';
                                            }
                                            $('.load-more:visible').before(content);
                                        }
                                    });
                            }
                        }
                        isLoading = false;
                        var body = $('body');
                        $('.alpha').width(body.width()).height(body.height());
                    } else {    // simple loading status indication
                        var m = i % 3;
                        var dots = '';
                        for (var j = 0; j < m; j++) {
                            dots += '.';
                        }
                        $('.load-more:visible').html('Loading more.' + dots);
                        i++;
                    }
                }, 500);
            }
        });
    }

    // post new news comment
    $('.js-post-news-comment').bind('click', function() {
        $(this).parents('.post-area').after('<div class="news-comment"><img src="/i/feed-photo.png" alt="Handle name" class="float-left" /><div class="content"><div class="meta"><span class="float-right">23 Hours</span><a href="UserProfile-nonfriendprofilepage.html">Handle name</a></div><p>' + $(this).parent().siblings('.textarea').val() + '</p><div class="button-holder"><a href="javascript:;" class="reply">Reply</a><a href="javascript:;" class="like">24 Likes</a></div></div></div>');
        disableTextareaResize();
    });

    var originalPost = '';
    // edit/remove feed post
    $('.js-edit-comment').live('click', function () {
        if ($(this).text() == 'Edit') {
            $(this).text('Done');
            originalPost = $(this).parent().prev().children().val();
            $(this).parent().prev().children().attr('disabled', false);
        } else {
            _this = $(this);
            var textArea = $(this).parent().prev().children();
            $.post('/updateWallPost', {
                wallPostId : _this.prev('.wallPostId').val(),
                detail : textArea.val()
            }).success(function(res) {
                res = JSON.parse(res);
                _this.text('Edit');
                textArea.attr('disabled', true);
                if(!res.updated) {
                    textArea.val(originalPost);
                    showMsg('ALERT', 'Can not update post');
                } else {
                    textArea.val(res.detail);
                }
            }).error(function() {
                textArea.val(originalPost);
                _this.text('Edit');
                textArea.attr('disabled', true);
                showMsg('ALERT', 'Can not update post');
            });
        }
    });
    // remove comment
    $('.js-remove-comment').live('click', function () {
        _this = $(this);
        if (confirm('Do you really want to remove the post?')) {
            $.ajax({
                url: '/wallPost',
                type: 'DELETE',
                data : {
                    wallPostId : _this.prev().prev('.wallPostId').val()
                },
                success: function(res) {
                    res = JSON.parse(res);
                    if(!res.deleted) {
                        showMsg('ALERT', 'Can not delete post');
                    } else {
                        _this.parents('.feeds').next().remove();
                        _this.parents('.feeds').remove();
                    }
                },
                error : function() {
                    showMsg('ALERT', 'Can not delete post');
                }
            });
        }
    });

    var originalComment = '';
    // edit/remove feed comment
    $('.js-edit-post-comment').live('click', function () {
        if ($(this).text() == 'Edit') {
            $(this).text('Done');
            originalComment = $(this).parent().prev().children().val();
            $(this).parent().prev().children().attr('disabled', false);
        } else {
            _this = $(this);
            var textArea = $(this).parent().prev().children();
            $.post('/wallPost/editComment', {
                wallPostId : _this.parents('ul.feed-comment').prev('div.feeds').find('.wallPostId').val(),
                wallPostCommentId : _this.prev('.wallPostCommentId').val(),
                text : textArea.val()
            }).success(function(res) {
                res = JSON.parse(res);
                _this.text('Edit');
                textArea.attr('disabled', true);
                if(!res.updated) {
                    textArea.val(originalComment);
                    showMsg('ALERT', 'Can not update comment');
                } else {
                    textArea.val(res.text);
                }
            }).error(function() {
                textArea.val(originalComment);
                _this.text('Edit');
                textArea.attr('disabled', true);
                showMsg('ALERT', 'Can not update comment');
            });
        }
    });
    $('.js-remove-post-comment').live('click', function () {
        _this = $(this);
        if (confirm('Do you really want to remove the comment?')) {
            $.ajax({
                url: '/wallPost/comment',
                type: 'DELETE',
                data : {
                    wallPostId : _this.parents('ul.feed-comment').prev('div.feeds').find('.wallPostId').val(),
                    wallPostCommentId : _this.prev().prev('.wallPostCommentId').val()
                },
                success: function(res) {
                    res = JSON.parse(res);
                    if(!res.deleted) {
                        showMsg('ALERT', 'Can not delete comment');
                    } else {
                        var countLink =  _this.parents('ul.feed-comment').prev('div.feeds').find('.comment-count');
                        var count = parseInt(countLink.html(), 10);
                        countLink.html(count - 1);
                        _this.parents('li.clearfix').remove();
                    }
                },
                error : function() {
                    showMsg('ALERT', 'Can not delete comment');
                }
            });
        }
    });


    // post new post comment
    if ($('.profile-area').length) {
        $('.js-post-comment').live('keydown', function (e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                var _this = $(this);
                $.post('/wallPost/newComment', {
                    wallPostId : _this.parents('ul.feed-comment').prev('div.feeds').find('.wallPostId').val(),
                    text : _this.val()
                }).success(function(res) {
                    res = JSON.parse(res);
                    if(!res.created) {
                        _this.val('post comment here').trigger('blur');
                        disableTextareaResize();
                        showMsg('ALERT', 'Can not create comment');
                    } else {
                        var countLink =  _this.parents('ul.feed-comment').prev('div.feeds').find('.comment-count');
                        var count = parseInt(countLink.html(), 10);
                        countLink.html(count + 1);
                        var content =
                            '<li class="clearfix">' +
                                '<img src="/i/comment-photo.png" alt="" />' +
                                '<a href="/userPublicProfile/' + res.comment.user + '">' + res.comment.user + '</a>';
                        if(res.comment.user === res.username) {
                            content +=
                                '<p><textarea class="textarea self-comment" disabled="disabled" rows="" cols="" style="resize: none;">' + res.comment.text + '</textarea>' +
                                '</p>' +
                                    '<div class="editComment">' +
                                    '<input type="hidden" class="wallPostCommentId" value="' + res.comment._id + '" />' +
                                    '<a class="js-edit-post-comment" href="javascript:;">Edit</a>&nbsp;|&nbsp;' +
                                    '<a class="js-remove-post-comment" href="javascript:;">Remove</a>' +
                                '</div>';
                        } else {
                            content += '<p>' + res.comment.text + '</p>';
                        }

                        content += '</li>';
                        _this.parent().before(content);
                        _this.val('post comment here').trigger('blur');
                        disableTextareaResize();
                    }
                }).error(function() {
                    _this.val('post comment here').trigger('blur');
                    disableTextareaResize();
                    showMsg('ALERT', 'Can not create comment');
                });
            }
        });
    }

    var originalStatus = '';
    // edit status in own profile
    $('.js-edit-status').bind('click', function () {
        $(this).parent().addClass('is-edit-mode');
        $(this).siblings('.js-edit-save').removeClass('is-hidden');
        $(this).siblings('.js-edit-cancel').removeClass('is-hidden');
        $(this).siblings('textarea').val($(this).siblings('.textarea-holder__text').text());
        originalStatus = $(this).siblings('.textarea-holder__text').text();
    });
    // edit status in own profile
    $('.js-edit-cancel').bind('click', function() {
        $(this).parent().removeClass('is-edit-mode');
        $(this).siblings('.js-edit-save').addClass('is-hidden');
        $(this).addClass('is-hidden');
        $('div.textarea-holder__text').text(originalStatus);
    });
    // edit status in own profile
    $('.js-edit-save').bind('click', function() {
        $(this).parent().removeClass('is-edit-mode');
        $(this).addClass('is-hidden');
        $(this).siblings('.js-edit-cancel').addClass('is-hidden');

        var _this = $(this);
        $.post('/social/editStatus', {
            statusText : _this.siblings('.textarea').val()
        }).success(function(res) {
                res = JSON.parse(res);
                if(!res.updated) {
                    _this.siblings('.textarea-holder__text').text(originalStatus);
                    showMsg('ALERT', 'Can not update status');
                } else {
                    _this.siblings('.textarea-holder__text').text(res.statusText);
                }
            }).error(function() {
                _this.siblings('.textarea-holder__text').text(originalStatus);
                showMsg('ALERT', 'Can not update status');
            });
    });

    // file uploader.
    $('.file-upload-placeholder').focus(function() {
        $(this).blur();
    });

    $('.js-profile-friends').delegate('.friend-request__photo, .username', 'mouseover', function() {
        var popup = $('.firend-request__info');
        popup.show();
        var parent = $(this).parents('.js-friend-request').eq(0);
        var username = parent.find('.username').html();
        var createDate = new Date(parent.find('.createdDate').val());
        popup.find('.usernameLink').html(username);
        popup.find('.usernameLink').attr('href', '/userPublicProfile/' + username);
        popup.find('.memberSince').html('Member since ' + (months[createDate.getMonth()]) + ' ' + (1900 + createDate.getYear()));
        popup.find('.fullProfileLink').attr('href', parent.find('.friend-request__photo').attr('href'));
        var imgSrc = parent.find('.friend-request__photo img').attr('src');
        popup.find('div.inforblock:eq(0) img').attr('src', imgSrc);
        var offset = parent.offset();
        popup.css({
            left: offset.left + 200,
            top: offset.top + 26
        });
        if (window.timer) {
            window.clearTimeout(window.timer);
        }
    });
    $('.js-profile-friends').delegate('.friend-request__photo, .username', 'mouseout', function() {
        var popup = $('.firend-request__info');
        window.timer = window.setTimeout(function() {
            popup.hide();
        }, 500);
    });
    $(document).delegate('.firend-request__info', 'mouseover', function() {
        window.clearTimeout(window.timer);
    });
    $(document).delegate('.firend-request__info', 'mouseout', function() {
        var popup = $('.firend-request__info');
        window.timer = window.setTimeout(function() {
            popup.hide();
        }, 500);
    });
    // footer social buttons hover
    $('.footer-bottom .social-links li').hover(
        function() {
            $(this).css('background-image', 'url(/i/circle-hover.png)');
        },
        function() {
            $(this).css('background-image', 'url(/i/circle.png)');
        }
    );
    disableTextareaResize();

    // fix ie8 fadeIn/fadeOut
    if ($.browser.msie && $.browser.version == 8) {
        $('.home-carousel .content').children().css('filter', 'inherit');
    }

    // resize alpha
    $(window).bind('resize', function() {
        var body = $('body');
        $('.alpha').width(body.width()).height(body.height());
    });
    $('.private-profile__table-content table th span').click(function() {
        var checkbox = $(this).siblings('.js-chk:visible');
        checkbox.trigger('click');
    });
    if(0 === $('.validateError div').length) {
        $('.validateError').hide();
    }
    $('#dateOfBirth').focus(function() {
        if($(this).val() === 'yyyy/mm/dd') {
            $(this).val('');
        }
    });
    $('#dateOfBirth').blur(function() {
        if(isEmpty($(this).val())) {
            $(this).val('yyyy/mm/dd');
        }
    });
    // image extensions. If needed, they can be modified
    var _validImgExtensions = ["jpg", "jpeg", "bmp", "gif", "png", "ico", "tif", "tiff"];
    // video extensions. If needed, they can be modified
    var _validVideoExtensions = ["mp4", "3gp", "ogm", "mkv", "rmvb", "rm", "wmv", "wma", "asf", "mov", "mpg", "avi"];
    if($('#addAttachment').length) {
        $('#addAttachment').css({"opacity": 0});
        var isPhoto = true;
        // inits ajax upload
        ajaxUpload = new AjaxUpload('addAttachment', {
            action: '/social/attachments/' + $('#username').val(),
            name: 'attachment',
            data: {
                description : 'description'
            },
            onSubmit: function(file, extension){
                if(isPhoto) {
                    if(_validImgExtensions.indexOf(extension) < 0) {
                        showMsg('ALERT', 'Please choose an image file!');
                        return false;
                    }
                } else {
                    if(_validVideoExtensions.indexOf(extension) < 0) {
                        showMsg('ALERT', 'Please choose a video file!');
                        return false;
                    }
                }
            },
            onComplete : function(file, res){
                $('<li></li>').appendTo($(isPhoto ? '.photos' : '.videos')).text(file);
                addAttachment(JSON.parse($(res).html()).attachmentId);
            },
            onError: function(err,err2){
                showMsg('ALERT', 'Can not upload file.');
            }
        });
        ajaxUpload._createInput();
        $('.addPhotos').click(function() {
            isPhoto = true;
            $('input[name="attachment"]').attr('accept', 'image/*');
            $('input[name="attachment"]').click();
        });
        $('.addVideos').click(function() {
            isPhoto = false;
            $('input[name="attachment"]').attr('accept', 'video/*');
            $('input[name="attachment"]').click();
        });
        /**
         * Adds attachment to the specified input field.
         *
         * @param {String} id the id of the attachment
         */
        function addAttachment(id) {
            var attachments = $('input[name="attachments"]').val();
            if(attachments) {
                attachments += ',';
            }
            attachments += id;
            $('input[name="attachments"]').attr('value',attachments);
        }
    }
    if($('#addPhoto').length) {
        $('.js-browse').click(function() {
            $('input[name="attachment"]').attr('accept', 'image/*');
            $('input[name="attachment"]').click();
        });
        $('#addPhoto').css('opacity', '0');
        // inits the ajax upload to upload files
        ajaxUpload = new AjaxUpload('#addPhoto', {
            action: '/social/attachments/' + $('#username').val(),
            name: 'attachment',
            data: {
                description : 'description'
            },
            onChange : function(filename) {
                $('.photoPath').val(filename);
            },
            onSubmit: function(file, extension){
                if(_validImgExtensions.indexOf(extension) < 0) {
                    showMsg('ALERT', 'Please choose an image file!');
                    return false;
                }
            },
            onComplete : function(file, res){
                var id = JSON.parse($(res).html()).attachmentId;
                $('#editConfiguration .photo').val('/userPrivateProfile/getProfilePicture/' + id);
                var img = $("<img style='width: 110px; height: 80px;' />");
                $('#photo-sec img').remove();
                $('#photo-sec').prepend(img);
                loadImg(img, '/userPrivateProfile/getProfilePicture/' + id);
                saveProfileConfiguration(true);
            },
            onError: function(err,err2){
                showMsg('ALERT', 'Can not upload photo now, please try again later.');
            }
        });
        ajaxUpload._createInput();
        $('.addPhotos').click(function() {
            $('input[name="attachment"]').click();
        });
        // remove photo of user
        $('.js-remove').click(function() {
            var _this = $(this);
            var photoPath = $('#editConfiguration .photo').val();
            if(photoPath.indexOf('/userPrivateProfile/getProfilePicture/') != 0) {
                showMsg('ALERT', 'Can not remove an external Picture!');
                return;
            }
            var photoId = photoPath.substr('/userPrivateProfile/getProfilePicture/'.length);
            $.ajax({
                url : '/userPrivateProfile/removeProfilePicture/' + photoId,
                type : 'DELETE',
                dataType : 'json',
                success : function(res) {
                    _this.siblings('input:eq(0)').val('');
                    _this.siblings('input:eq(1)').val('/i/photo.png');
                    loadImg($('#photo-sec img'), '/i/photo.png');
                    saveProfileConfiguration(true);
                },
                error : function() {
                    showMsg('ALERT', 'Can not remove Picture now, please try again later!');
                }
            });
        });
    }
    // send message
    $('#sendMessage').click(function () {
        var _this = $(this);
        var msg = $('form.send-message textarea[name="message"]').val();
        if(isEmpty(msg)) {
            showMsg('ALERT', 'Please enter the message to send');
            return;
        }
        $('.alpha').css('display', 'none');
        $(this).parents('.popup').css('display', 'none');
        jQuery.ajax({
            type : 'POST',
            url : '/social/message/create',
            dateType : 'json',
            data : {
                message: msg,
                target : $('form.send-message input#to').val(),
                attachments : $('form.send-message input[name="attachments"]').val(),
                type: 'OUTGOING',
                userId : $('#toUserId').val()
            },
            success: function (data, textStatus, jqXHR) {
                data = JSON.parse(data);
                if(!data.created) {
                    showMsg('ALERT', 'Error occur: ' + data.errMsg);
                }

                $('.alpha').css('display', 'none');
                _this.parents('.popup').css('display', 'none');
            },
            error: function (data, textStatus, jqXHR) {
                showMsg('ALERT', 'Error occur: ' + data.responseText);
                $('.alpha').css('display', 'none');
                _this.parents('.popup').css('display', 'none');
            }
        });
    });
    // add friend message
    $('#addFriendMessage').click(function(){
        var _this = $(this);
        var msg = $('div.add-friend textarea#message').val();
        if(isEmpty(msg)) {
            showMsg('ALERT', 'Please enter the message to send');
            return;
        }
        $('.alpha').css('display', 'none');
        $(this).parents('.popup').css('display', 'none');
        var username = $('#username').val();
        jQuery.ajax({
            type : 'POST',
            url : '/social/friend/' + $('#addFriendUsername').val() + '/add',
            dateType : 'json',
            data : {
                text: msg,
                userId : $('#addFriendId').val(),
                showInWall : $('input#showInWall').prev('a').hasClass('jqTransformChecked')
            },
            success: function (data, textStatus, jqXHR) {
                data = JSON.parse(data);
                if(!data.created) {
                    showMsg('ALERT', 'Error occur: ' + data.errMsg);
                }
                $('.alpha').css('display', 'none');
                _this.parents('.popup').css('display', 'none');
            },
            error: function (data, textStatus, jqXHR) {
                if(data.responseText.indexOf('is already your friend')) {
                    showMsg('ALERT', 'Error occur: ' + username + ' is already your friend. Please refresh the page');
                } else {
                    showMsg('ALERT', 'Error occur: can not add ' + username + ' as a friend');
                }
                $('.alpha').css('display', 'none');
                _this.parents('.popup').css('display', 'none');
            }
        });
    });
    /**
     * Find the specified friend row.
     * @param {String} friendname the friend name
     * @return {Boolean} true if it can find the friend row; otherwise, return false
     */
    function findFriendRow(friendname) {
        var found = null;
        $('.js-friend-request').each(function(idx, friend) {
            if($.trim($(friend).find('.username').html()) == friendname) {
                found = $(friend);
                return true;
            }
        });
        return found;
    }
    // confirm the friend/unblock the friend
    $('.confirmConfirmFriend, .confirmUnblockFriend').live('click', function(){
        var _this = $(this);
        var friendId = _this.attr('name');
        var url = '/social/friend/' + friendId +'/confirm';
        var friendname = _this.data('friend');
        jQuery.ajax({
            url: url,
            type: 'PUT',
            data:{
                postToWall:'on',
                uname: friendname
            },
            success: function (data, textStatus, jqXHR) {
                var found = findFriendRow(friendname);
                if(found != null) {
                    if(_this.hasClass('confirmUnblockFriend')) {
                        found.remove();
                    } else {
                        var parent = found.find('.friend-request__content');
                        var userId = parent.find('.js-confirm-friend').data('userid');
                        parent.find('.js-confirm-friend').remove();
                        parent.find('.ignore-friend').remove();
                        parent.prepend('<a data-friend="' + friendname + '" name="' + friendId + '" href="javascript:;" class="button float-right js-remove-friend">REMOVE FRIEND</a>');
                        parent.prepend('<a data-friend="' + friendname + '" name="' + friendId + '" href="javascript:;" class="button float-right js-block-friend">BLOCK</a>');
                    }
                }
            },
            error: function (data, textStatus, jqXHR) {
                showMsg('ALERT', 'Error occur : ' + data.responseText);
            }
        });
    });
    // blocks friend
    $('.confirmBlockFriend').live('click', function(){
        var _this = $(this);
        var friendId = _this.attr('name');
        var url = '/social/friend/' + friendId +'/block';
        var friendname = _this.data('friend');
        jQuery.ajax({
            url: url,
            type: 'PUT',
            data:{
                postToWall:'on',
                uname: friendname
            },
            success: function (data, textStatus, jqXHR) {
                var found = findFriendRow(friendname);
                if(found != null) {
                    found.remove();
                }
            },
            error: function (data, textStatus, jqXHR) {
                showMsg('ALERT', 'Error occur : ' + data.responseText);
            }
        });
    });
    // confirm remove friend
    $('.confirmRemoveFriend').live('click', function(){
        var _this = $(this);
        var url = '/social/friend/' + _this.attr('name');
        var friendname = _this.data('friend');
        jQuery.ajax({
            url: url,
            type: 'DELETE',
            data:{
                postToWall:'on',
                uname: friendname
            },
            success: function (data, textStatus, jqXHR) {
                var found = findFriendRow(friendname);
                if(found != null) {
                    found.remove();
                }
            },
            error: function (data, textStatus, jqXHR) {
                showMsg('ALERT', 'Error occur : ' + data.responseText);
            }
        });
    });
});
/**
 * Loads image from the url.
 * @param {Object} img the image object
 * @param {String} url the image url
 */
function loadImg(img, url) {
    img.attr('src', url).load(function() {
        if (this.complete && typeof this.naturalWidth != "undefined" && this.naturalWidth != 0) {
            return;
        }
        showMsg('ALERT', 'Can not load photo');
    });
}
/**
 * Search memmber by reloading the page.
 */
function searchMember() {
    window.location.href = '/membersearch?member=' + $('#member').val() ;
}
/**
 * Logs out the user.
 */
function logout() {
    $('#logoutForm').submit();
}
/**
 * Checks value is empty or not.
 *
 * @param {String} val the value
 * @return {Boolean} true if it's empty; otherwise, return false
 */
function isEmpty(val) {
    if($.trim(val).length) {
        return false;
    }
    return true;
}
/**
 * Login with specified user/password.
 *
 * @param {Boolean} popup flag to login from pop up
 */
function login(popup) {
    var err = false;
    $('.validateError').empty();
    $('.validateError').hide();
    if (popup) {
        if(isEmpty($('#loginPopup input#username1').val())) {
            err = true;
            $('#loginPopupError').append('<div>*Username or Email is required.</div>');
        }
        if(isEmpty($('#loginPopup input#password1').val())) {
            err = true;
            $('#loginPopupError').append('<div>*Password is required.</div>');
        }
        if(err) {
            $('#loginPopupError').show();
            return;
        }
        $('#loginPopup').submit();
    } else {
        if(isEmpty($('#loginForm input#username').val())) {
            err = true;
            $('#loginFormError').append('<div>*Username or Email is required.</div>');
        }
        if(isEmpty($('#loginForm input#password').val())) {
            err = true;
            $('#loginFormError').append('<div>*Password is required.</div>');
        }
        if(err) {
            $('#loginFormError').show();
            return;
        }
        $('#loginForm').submit();
    }
}

/**
 * Reset password.
 */
function resetPassword() {
    var err = false;

    $('.validateError').empty();
    $('.validateError').hide();

    var invalidUsername = isEmpty($('#handle').val()) || ('Username here' == $('#handle').val());
    if(invalidUsername) {
        err = true;
        $('#recoverPasswordFormError').append('<div>*Username is required.</div>');
    }
    var invalidEmail = isEmpty($('#email').val()) || ('email' == $('#email').val());
    if(invalidEmail) {
        err = true;
        $('#recoverPasswordFormError').append('<div>*Email Address is required.</div>');
    } else if(!isEmail($('#email').val())) {
        err = true;
        $('#recoverPasswordFormError').append('<div>*Email Address is not a valid email address.</div>');
    }

    var invalidConfirmEmail = isEmpty($('#email2').val()) || ('email' == $('#email2').val());
    if(invalidConfirmEmail) {
        err = true;
        $('#recoverPasswordFormError').append('<div>*Confirm Email is required.</div>');
    }
    if(!invalidEmail && !invalidConfirmEmail &&
        ($('#email').val() !== $('#email2').val())) {
        err = true;
        $('#recoverPasswordFormError').append('<div>*Confirm Email and Email should match.</div>');
    }

    if(err) {
        $('#recoverPasswordFormError').show();
        return;
    }
    $('#recoverPasswordForm').submit();
}

/**
 * Checks it's email or not.
 *
 * @param {String} email the email address
 * @return {Boolean} true if it's a valid email address
 */
function isEmail(email) {
    var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}
/**
 * Signs up.
 */
function signUp() {
    var err = false;

    $('.validateError').empty();
    $('.validateError').hide();
    if(isEmpty($('#emailAddress').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Email Address is required.</div>');
    } else if(!isEmail($('#emailAddress').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Email Address is not a valid email address.</div>');
    }
    if(isEmpty($('#username').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Username is required.</div>');
    }
    if(isEmpty($('#password').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Password is required.</div>');
    }
    if(isEmpty($('#confirmPassword').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Confirm Password is required.</div>');
    }
    if(!isEmpty($('#username').val()) && !isEmpty($('#confirmPassword').val()) &&
        ($('#confirmPassword').val() !== $('#password').val())) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Confirm Password and Password should match.</div>');
    }
    if (0 === $('#termSection .jqTransformChecked').length) {
        err = true;
        $('#signUpFormValidateError').append('<div>*Must accept the term to sign up.</div>');
        $('#signUpFormValidateError').show();
    }
    if(err) {
        $('#signUpFormValidateError').show();
        return;
    }
    if($('#dateOfBirth').val() === 'yyyy/mm/dd') {
        $('#dateOfBirth').val('');
    }
    $('#signUpForm').submit();
}
/**
 * change content of home carousel.
 * @param {Number} index the index of the current content
 */
var changeContent = function (index) {
    var index = $.jcarousel.intval($('.carousel .is-current').attr('jcarouselindex'));
    var size = $('.home-carousel .content').length;
    index = (index - 1) % size;
    index = index < 0 ? size + index : index;
    $('.home-carousel .content:visible').fadeOut('fast', function() {
        $('.home-carousel .content:eq(' + index + ')').fadeIn('fast');
    });
};
/**
 * Inits carousel.
 */
function initCarousel() {
    if ($('.carousel').length > 0) {
        var isFinished = true; // is used to ensure the animation has finished before doing anything else
        $('.carousel ul').jcarousel({
            vertical: true,
            scroll: 1,
            wrap: 'circular',
            setupCallback: function() {
                // add current style
                $('.carousel ul li:eq(2)').addClass('is-current');
                $('.jcarousel-list-vertical').css('overflow','auto');
                $('.jcarousel-list-vertical').css('overflow-y','hidden');
                $('.jcarousel-list-vertical').css('padding','0 18px 0 35px');
                // ride the carousel
                $('.jcarousel-prev-vertical').live('click', function() {
                    if (isFinished) {
                        isFinished = false;
                        $('.carousel ul li.is-current').prev().addClass('is-current');
                        $('.carousel ul li.is-current:eq(1)').removeClass('is-current');
                        changeContent();
                    }
                });
                $('.jcarousel-next-vertical').live('click', function() {
                    if (isFinished) {
                        isFinished = false;
                        $('.carousel ul li.is-current').next().addClass('is-current');
                        $('.carousel ul li.is-current:eq(0)').removeClass('is-current');
                        changeContent();
                    }
                });
            },
            itemFirstInCallback: function() {
                isFinished = true;
            },
            initCallback: function(carousel){
                // click on the item
                $('.carousel ul li').bind('click', function() {
                    var index = $.jcarousel.intval($(this).attr('jcarouselindex'));
                    $(this).addClass('is-current');
                    $(this).siblings().removeClass('is-current');
                    carousel.scroll($.jcarousel.intval($(this).attr('jcarouselindex') - 2));
                    changeContent();
                });
            }
        });
    }
}
/**
 * Get text from a value.
 * @param {Mixed} val the value
 * @return {String} the value as string
 */
function getTxt(val) {
    return val ? val : '';
}
//disable textarea resize in modern browsers
var disableTextareaResize = function() {
    $('textarea').css('resize', 'none');
};

/**
 * Handlers the scroll loading.
 *
 * @param {Object} e the event object
 */
function handleBinding(e) {
    e.stopImmediatePropagation();
    e.stopPropagation();
    var pos_start = $(this).offset().top;
    var pos_end = $(this).outerHeight(false) + pos_start;

    var child = $(this).find('.js-msg-load-more');
    child.removeAttr('stoploading');
    var loading = child.attr('isloading');
    var pos = child.offset();
    var top = pos.top;

    /**
     * Handle the scroll loading.
     * @return null
     */
    function handleLoading() {
        var ticks = child.data('ticks');
        var stoploading = child.attr('stoploading');
        if (stoploading == 'true') {
            child.removeAttr('isloading');
            child.show();
            return;
        }
        if (ticks == 3) {
            child.removeAttr('isloading');
            var p = child.parent();
            p.find('.js-cache-load').each(function() {
                var obj = $(this).clone();
                obj.removeClass('is-selected');
                obj.insertBefore(child);
                obj.addClass('is-lazy-load');
            });
            return;
        } else if (ticks == 6) {
            child.removeAttr('isloading');
            child.parent().unbind('scroll');
            child.hide();
            return;
        }
        var text = 'Loading more';
        var value = ticks % 3 + 1;
        for (var i = 0; i < value; i++) {
            text += '.';
        }
        ticks++;
        child.data('ticks', ticks);
        child.text(text);
        window.setTimeout(handleLoading, 500);
    }
    if (top < pos_start || top > pos_end || loading == 'true') {
        return;
    }
    child.attr('isloading', 'true');
    var ticks = child.data('ticks');

    if (!ticks) {
        child.data('ticks', 0);
    } else {
        child.data('ticks', 4);
    }
    window.setTimeout(handleLoading, 500);
}
/**
 * Handle the scroll loading.
 * @param {Object} parent the parent node
 */
function handleScrollLoading(parent) {
    parent.scrollTop(0);
    parent.unbind('scroll');
    var child = parent.find('.js-msg-load-more');
    if (child.attr('disabled') == 'disabled') {
        return;
    }
    child.data('ticks', 0);
    child.attr('stoploading', 'true');
    child.show();
    parent.bind('scroll', handleBinding);
}

/**
 * save basic data.
 */
function saveBasicData() {
    var err = false;

    $('.validateError').empty();
    $('.validateError').hide();

    if(isEmpty($('#editBasicData .emailAddress').val())) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Email Address is required.</div>');
    } else if(!isEmail($('#editBasicData .emailAddress').val())) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Email Address is not a valid email address.</div>');
    }
    if(isEmpty($('#editBasicData .password').val())) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Password is required.</div>');
    }
    if(isEmpty($('#editBasicData .confirmPassword').val())) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Confirm Password is required.</div>');
    }
    if(!isEmpty($('#editBasicData .password').val()) && !isEmpty($('#editBasicData .confirmPassword').val()) &&
        ($('#editBasicData .confirmPassword').val() !== $('#editBasicData .password').val())) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Confirm Password and Password should match.</div>');
    }
    var birthDate = $('#editBasicData .dateOfBirth').val();
    if(!isEmpty(birthDate) && (String(new Date(birthDate))).indexOf('Invalid') >= 0) {
        err = true;
        $('#editBasicDataValidateError').append('<div>*Date of Birth is not a valid date.</div>');
    }
    if(err) {
        $('#editBasicDataValidateError').show();
        return;
    }
    var date = $('#editBasicData .dateOfBirth').datepicker('getDate');
    var dateStr = $.datepicker.formatDate('yy/mm/dd', date);
    $.ajax({
        url : '/userPrivateProfile/saveBasicData',
        type : 'POST',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify({
            userId : $('#editBasicData .userId').val(),
            password : $('#editBasicData .password').val(),
            emailAddress : $('#editBasicData .emailAddress').val(),
            dateOfBirth : dateStr
        }),
        success : function(res) {
            switchToReadMode();
        },
        error : function() {
            showMsg('ALERT', 'Can not save Basic Data now, please try again later!');
        }
    });
}

/**
 * Save profile configuration.
 *
 * @param {Boolean} onlyAvatar flag to indicate only save avatar or not
 */
function saveProfileConfiguration(onlyAvatar) {
    var data = {
        userId : $('#editConfiguration .userId').val(),
        photo : $('#editConfiguration .photo').val(),
        quote : $('#editConfiguration .quote').val(),
        firstName : $('#editConfiguration .firstName').val(),
        lastName : $('#editConfiguration .lastName').val(),
        address : $('#editConfiguration .address').val(),
        city : $('#editConfiguration .city').val(),
        stateId : $('#editConfiguration .state').val(),
        zip : $('#editConfiguration .zip').val(),
        freeFormText : $('#editConfiguration .freeFormText').val()
    };
    if(onlyAvatar) {
        data = {
            userId : $('#editConfiguration .userId').val(),
            photo : $('#editConfiguration .photo').val()
        };
    }
    $.ajax({
        url : '/userPrivateProfile/saveConfiguration',
        type : 'POST',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify(data),
        success : function(res) {
            if(onlyAvatar) {
                loadImg($('.userAvatar'), $('#photo-sec img').attr('src'));
                return;
            } else {
                switchToReadMode();
                loadImg($('.userAvatar'), $('#photo-sec img').attr('src'));
            }
        },
        error : function() {
            showMsg('ALERT', 'Can not save Profile Configuration now, please try again later!');
        }
    });
}
/**
 * Save notification data.
 */
function saveNotificationData() {
    var notificationData = [];
    $('#notificationDataTable tbody tr').each(function(idx, row) {
        notificationData.push({
            notificationDataId : $(row).data('id'),
            sendNotification : $(row).find('td:eq(1) a').hasClass('is-checked'),
            emailFormat : ($(row).find('td:eq(2) a:eq(0)').hasClass('is-checked') ? "HTML" : "PLAIN_TEXT")
        });
    });
    $.ajax({
        url : '/userPrivateProfile/saveNotifications',
        type : 'POST',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify(notificationData),
        success : function(res) {
            switchToReadMode();
        },
        error : function() {
            showMsg('ALERT', 'Can not save Notification Data now, please try again later!');
        }
    });
}
/**
 * Saves sharing options.
 */
function saveSharingOptions() {
    var sharingOptions = [];
    $('#sharingOptionsDataTable tbody tr').each(function(idx, row) {
        sharingOptions.push({
            shareableUserDataId : $(row).data('id'),
            shareableOptions : {
                publicProfile: $(row).find('td:eq(1) a').hasClass('is-checked'),
                privateProfile: $(row).find('td:eq(2) a').hasClass('is-checked'),
                shareOnFacebook: $(row).find('td:eq(3) a').hasClass('is-checked'),
                shareOnTwitter: $(row).find('td:eq(4) a').hasClass('is-checked'),
                shareWithFriends: $(row).find('td:eq(5) a').hasClass('is-checked')
            }
        });
    });
    $.ajax({
        url : '/userPrivateProfile/saveSharingOptions',
        type : 'POST',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify(sharingOptions),
        success : function(res) {
            switchToReadMode();
        },
        error : function() {
            showMsg('ALERT', 'Can not save Sharing Options now, please try again later!');
        }
    });
}
/**
 * Unregister user from this site.
 */
function unregisterUser() {
    $.ajax({
        url : '/userAccount',
        type : 'DELETE',
        dataType : 'json',
        contentType : "application/json; charset=utf-8",
        data : JSON.stringify({
            userId : $('#unregisterUser .userId').val()
        }),
        success : function(res) {
            showPopup('.popup__unregister-confirm');
        },
        error : function() {
            showMsg('ALERT', 'Can not unregister user now, please try again later!');
        }
    });
}
/**
 * Switch to read data mode.
 */
function switchToReadMode() {
    var parent = $('.private-profile__content-edit__button-bar a.js-button-save').parent().parent().parent();
    parent.find('.is-symbol-checked').each(function() {
        var next = $(this).next();
        if (next.hasClass('is-checked')) {
            $(this).removeClass('is-symbol-unchecked');
        } else {
            $(this).addClass('is-symbol-unchecked');
        }
    });
    parent.find('.email-format').each(function() {
        $(this).text($(this).next().find('a.is-checked').text());
    });

    var target = parent.find('.private-profile__content');

    parent.find('input, textarea').each(function() {
        var p = $(this).parent();
        var labels = p.attr('class')
        if (!labels) {
            return;
        }
        labels = labels.split(' ');
        var key = '';
        for (var i = 0; i < labels.length; i++) {
            var label = labels[i];
            if (label.indexOf('js-item-') >= 0) {
                key = label;
                break;
            }
        }
        if (key.length > 0) {
            var itemwrapper = target.find('.' + key);
            var a = itemwrapper.find('a');
            if (a.length > 0) {
                a.attr('href', 'mailto:' + $(this).val());
                a.text($(this).val());
            } else {
                if ($(this).hasClass('js-calendar')) {
                    var date = $(this).datepicker('getDate');
                    var str = $.datepicker.formatDate('MM dd, yy', date);
                    itemwrapper.text(str);
                } else {
                    if ($(this).hasClass('textarea-bio')) {
                        var str = $(this).val().replace(/\n/g, '<br>');
                        itemwrapper.html(str);
                    } else {
                        itemwrapper.text($(this).val());
                    }
                }
            }
        }
    });
    parent.removeClass('is-edit-mode');
}